package util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public final class MyBatisUtil {
    private MyBatisUtil(){}

    private static SqlSession session;

    static {
        // 由于控制台项目本身就只有单线程，所以为了方便，直接创建一个SqlSession即可
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
            session = factory.openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> T getMapper(Class<T> clazz) {
        return session.getMapper(clazz);
    }

}
